package API.Stack;

import java.util.Iterator;

/**
 * Created by Lee on 2017/2/16 0016.
 */
public class ResizingArrayStack<Item> implements Iterable<Item>{
    private Item[] a; // stack entries
    private int N;//size

    public ResizingArrayStack() {
        a = (Item[]) new Object[1];
    }

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    /*
    * 如果使用空间已满，则将栈大小扩大为原来的二倍
    * */
    public void push(Item item) {
        if (N == a.length) {
            resize(2 * a.length);
        }
        a[N++] = item;
    }

    /*
    * 如果使用空间小于栈大小四分之一，则将栈大小缩小为原来的二分之一*/
    public Item pop() {
        Item item = a[--N];
        a[N] = null;
        if (N > 0 && N == a.length / 4) {
            resize(a.length/2);
        }
        return item;
    }

    /*重新定义栈大小
    * 避免内存浪费*/
    private void resize(int max) {
        Item[] temp = (Item[]) new Object[max];
        for (int i=0;i<N;i++) {
            temp[i]=a[i];
        }
        a=temp;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ReverseArrayIterator();
    }

    private class ReverseArrayIterator implements Iterator<Item> {
        private int i=N;
        @Override
        public boolean hasNext() {
            return i>0;
        }

        @Override
        public Item next() {
            return a[--i];
        }

        @Override
        public void remove() {
        }
    }
}
